<template>
    <div :class="{'ly-is-full':isFull}">
        <div class="tableSelect" ref="tableSelect">
            <el-form :inline="true" :model="formInline" label-position="left">
                <el-form-item label="关键词：">
                    <el-input size="default" clearable  v-model.trim="formInline.keyword"  maxlength="60" placeholder="关键词" @change="getData" style="width:200px"></el-input>
                </el-form-item>
                <el-form-item label="侧边可见：">
                    <el-select size="default" v-model="formInline.visible" clearable placeholder="请选择" @change="getData" style="width:120px">
                        <el-option
                            v-for="item in statusList1"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态：">
                    <el-select size="default" v-model="formInline.status" clearable placeholder="请选择" @change="getData" style="width:120px">
                        <el-option
                            v-for="item in statusList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label=""><el-button  @click="getData" type="primary" icon="Search" v-show="hasPermission(this.$route.name,'Search')">查询</el-button></el-form-item>
                <el-form-item label=""><el-button  @click="handleEdit('','reset')" icon="Refresh">重置</el-button></el-form-item>
                <el-form-item label="">
                    <el-button type="primary" @click="addMenu" icon="Plus" v-show="hasPermission(this.$route.name,'Create')">新增</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-table
                :max-height="tableHeight"
                border
                row-key="id"
                :data="tableData"
                ref="tableref"
                v-loading="loadingPage"
                style="width: 100%;"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column type="index" width="70"  label="序号" style="display: unset;">
                <template #default="scope">
                    <span v-text="getIndex(scope.$index)"></span>
                </template>
            </el-table-column>
            <el-table-column min-width="150" prop="name" label="菜单名称"></el-table-column>
            <el-table-column min-width="80" prop="icon" label="图标">
                <template #default="scope">
                    <el-icon :size="16" v-if="scope.row.icon">
                      <component :is="scope.row.icon" />
                    </el-icon>
                </template>
            </el-table-column>
            <el-table-column min-width="70" prop="order_num" label="排序"></el-table-column>
            <el-table-column min-width="160" prop="path" label="路由地址" show-overflow-tooltip=""></el-table-column>
            <el-table-column min-width="300" label="权限">
                <template #default="scope">
                    <span v-if="scope.row.menuPermission && scope.row.menuPermission.length > 0">
                        <span v-for="(item,index) in scope.row.menuPermission" :key="index">
                            {{item + (index < scope.row.menuPermission.length - 1 ? '/' : '')}}
                        </span>
                    </span>
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column min-width="100" label="侧边可见">
                <template #default="scope">
                    <el-tag v-if="scope.row.visible">是</el-tag>
                    <el-tag v-else type="danger">否</el-tag>
                </template>
            </el-table-column>
            <el-table-column min-width="90" label="状态">
                <template #default="scope">
                    <el-tag v-if="scope.row.status !== false" type="success">启用</el-tag>
                    <el-tag v-else type="danger">禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="200">
                <template #header>
                    <div style="display: flex;justify-content: space-between;align-items: center;">
                        <div>操作</div>
                        <div @click="setFull">
                            <el-tooltip content="全屏" placement="bottom">
                                <el-icon ><full-screen /></el-icon>
                            </el-tooltip>
                        </div>
                    </div>
                </template>
                <template #default="scope">
                    <span class="table-operate-btn" @click="handleEdit(scope.row,'edit')" v-show="hasPermission(this.$route.name,'Update')">编辑</span>
<!--                    <span class="table-operate-btn" @click="handleEdit(scope.row,'detail')" v-show="isShowBtn('menuManage','菜单管理','Retrieve')">详情</span>-->
                    <span class="table-operate-btn" @click="handleEdit(scope.row,'delete')" v-show="hasPermission(this.$route.name,'Delete')">删除</span>
                    <span class="table-operate-btn" @click="handleEdit(scope.row,'buttonConfig')" v-show="hasPermission(this.$route.name,'Retrieve') && (scope.row.menuPermission || scope.row.isautopm==1)">按钮配置</span>
                </template>
            </el-table-column>
        </el-table>
        <add-menu ref="addMenuFlag"  @refreshData="refreshData"></add-menu>
    </div>
</template>
<script>
    import addMenu from "./components/addMenu.vue";
    import {dateFormats,getTableHeight,setStorage} from "@/utils/util";
    import {apiSystemMenu,apiSystemMenuDelete} from '@/api/api'
    import XEUtils from "xe-utils";
    export default {
        components:{
            addMenu,
        },
        name:'menuManage',
        data() {
            return {
                isFull:false,
                tableHeight:260,
                loadingPage:false,
                formInline:{
                    keyword:'',
                    name:'',
                    status:'',
                    cache:'',
                    visible:'',
                    page:1,
                    limit:9999
                },
                pageparm: {
                    page: 1,
                    limit: 10,
                    total: 0
                },
                timers:[],
                tableData:[],
                statusList:[
                    {id:1,name:'启用'},
                    {id:0,name:'禁用'},
                ],
                statusList1:[
                    {id:1,name:'是'},
                    {id:0,name:'否'},
                ]
            }
        },
        methods:{
            // 表格序列号
            getIndex($index) {
                // (当前页 - 1) * 当前显示数据条数 + 当前行数据的索引 + 1
                return (this.pageparm.page-1)*this.pageparm.limit + $index +1
            },
            setFull(){
                this.isFull=!this.isFull
            },
            addMenu() {
                this.$refs.addMenuFlag.addMenuFn(null,'新增')
            },
            handleEdit(row,flag) {
                if(flag=='edit') {
                    this.$refs.addMenuFlag.addMenuFn(row,'编辑')
                }
                else if(flag == 'detail') {
                    this.$refs.addMenuFlag.addMenuFn(row,'详情')
                }
                else if(flag == 'buttonConfig') {
                    this.$router.push({name:'buttonConfig',query:{id:row.id,name:row.name}})
                }
                else if(flag=='delete') {
                    let vm = this
                    vm.$confirm('您确定要删除选中的菜单？',{
                        closeOnClickModal:false
                    }).then(()=>{
                        apiSystemMenuDelete(row.id).then(res=>{
                            if(res.code == 200) {
                                vm.$message.success(res.message)
                                vm.refreshData()
                            } else {
                                vm.$message.warning(res.message)
                            }
                        })

                    }).catch(()=>{

                    })
                }
                else if(flag=="reset"){
                    this.formInline = {
                        keyword:'',
                        name:'',
                        status:'',
                        cache:'',
                        visible:'',
                        page:1,
                        limit: 9999
                    }
                    this.pageparm={
                        page: 1,
                        limit: 10,
                        total: 0
                    }
                    this.getData()
                }
            },
            //获取列表
            async getData(){
                this.loadingPage = true
                console.log('🔍 开始查询菜单数据，查询参数:', this.formInline)
                
                // 准备查询参数，过滤空值
                const queryParams = { tree: true }
                
                // 只添加有值的查询参数
                if (this.formInline.keyword && this.formInline.keyword.trim()) {
                    queryParams.keyword = this.formInline.keyword.trim()
                }
                if (this.formInline.visible !== '' && this.formInline.visible !== null && this.formInline.visible !== undefined) {
                    queryParams.visible = this.formInline.visible
                }
                if (this.formInline.status !== '' && this.formInline.status !== null && this.formInline.status !== undefined) {
                    queryParams.status = this.formInline.status
                }
                
                console.log('🔍 实际发送的查询参数:', queryParams)
                
                // 获取菜单数据
                apiSystemMenu(queryParams).then(res => {
                    console.log('🔍 菜单查询响应:', res)
                    this.loadingPage = false
                    if(res.code == 200) {
                        // 检查是否有筛选条件
                        const hasFilter = queryParams.keyword || queryParams.visible !== undefined || queryParams.status !== undefined
                        
                        if (hasFilter) {
                            // 有筛选条件时，后端返回平铺结构，直接显示
                            this.tableData = res.data
                            console.log('✅ 筛选模式：显示平铺结构数据，共', res.data.length, '条记录')
                        } else {
                            // 没有筛选条件时，后端返回树形结构
                            this.tableData = res.data
                            console.log('✅ 树形模式：显示树形结构数据，共', res.data.length, '条记录')
                        }
                        
                        this.pageparm.total = res.data.length;
                    } else {
                        this.$message.warning(res.message)
                        console.error('❌ 菜单查询失败:', res.message)
                    }
                }).catch(error => {
                    this.loadingPage = false
                    console.error('❌ 菜单查询请求失败:', error)
                    this.$message.error('查询失败，请重试')
                })
            },
            refreshData(){
                this.getData()
                this.$Bus.emit('routeReload', true)
            },
            // 计算搜索栏的高度
            listenResize() {
				this.$nextTick(() => {
				    this.getTheTableHeight()
				})
			},
            getTheTableHeight(){
                this.tableHeight =  getTableHeight(this.$refs.tableSelect.offsetHeight-50)

            }
        },
        created() {
            this.getData()
        },
        mounted() {
            // 监听页面宽度变化搜索框的高度
            window.addEventListener('resize', this.listenResize);
            this.$nextTick(() => {
              this.getTheTableHeight()
            })
        },
        unmounted() {
              // 页面销毁，去掉监听事件
			window.removeEventListener("resize", this.listenResize);
        },
    }
</script>
<style lang="scss" scoped>
    .tableNav{
        overflow: hidden;
        margin-bottom: 20px;
    }
    /*::v-deep(.el-table__placeholder){*/
    /*    display: unset;*/
    /*}*/
</style>